/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;

public class CarerListFragment extends BaseFragment implements
		OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
	OnListFragmentSelectedListener mCallback;
	DataSources ds;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	String[] keys = new String[] { "userName", "carName", "plate", "tel",
			"companyNick" };
	ListView listView;
	protected JSONArray userListJosnAry = new JSONArray();

	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}

	public View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.carer_list, container, false);
		ds = new DataSources();
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);
		// adapter = new SimpleAdapter(getActivity(),
		// (List<Map<String, Object>>) contents, R.layout.list_item_carer,
		// keys, new int[] { R.id.textView1, R.id.textView2,
		// R.id.textView3, R.id.textView4, R.id.textView5 });
		// listView.setAdapter(adapter);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		view.findViewById(R.id.go_search).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						startActivity(GlobalVariable.getGlobalInstance().intent
								.setAction(ActivityActionName.SEARCH));
					}
				});
		view.findViewById(R.id.add_carer).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						GlobalVariable.getGlobalInstance().intent.putExtra(
								IntentExtraDataKey.USERID, -1);
						GlobalVariable.getGlobalInstance().intent.putExtra(
								IntentExtraDataKey.PLATE, "");
						getActivity()
								.startActivityForResult(
										GlobalVariable.getGlobalInstance().intent
												.setAction(ActivityActionName.CARER),
										IntentExtraDataKey.ACTIVITY_QUESTCODE_UPDATECARERINFO);

					}
				});
		initData(null);
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	int page;
	PullToRefreshView mPullToRefreshView;
	SimpleAdapter adapter;

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page++;
				getData(page);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getData(null);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	protected void initData(Integer _page) {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getData(null);

	}

	protected void getData(Integer _page) {
		ds.getAlluser(_page, new AjaxCallBack<String>() {
			public void onLoading(long count, long current) {
			}

			public void onSuccess(String t) {
				lg.i(TAG, t);
				int code = 0;
				String mesage = "";
				try {
					JSONObject result = new JSONObject(t);
					;
					code = result.optInt(webkey.code);
					mesage = result.optString(webkey.reason);

					JSONArray newJsonArray = result.optJSONArray(webkey.result);
					contents.removeAll(contents);
					if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
						userListJosnAry = null;
						userListJosnAry = newJsonArray;
					} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
						for (int i = 0; i < newJsonArray.length(); i++) {
							userListJosnAry.put(newJsonArray.opt(i));
						}
					}
					if (userListJosnAry == null) {
						userListJosnAry = new JSONArray();
					}
					int count = userListJosnAry.length();
					for (int i = 0; i < count; i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject temp = userListJosnAry.getJSONObject(i);
						for (String key : keys) {
							Object o = "";
							// "userName", "carName", "plate", "tel",
							// "companyNick"
							if (key.equals("carName")) {
								o = temp.optJSONObject("car").optString(
										"carName");
							} else if (key.equals("companyNick")) {
								o = temp.optJSONObject("company").optString(
										"companyNick");
							} else {
								o = temp.opt(key);
							}
							if (o == null || o.toString().equals("null")) {
								o = "";
							}
							map.put(key, o.toString());
						}
						contents.add(map);
					}
					if (adapter == null) {
						if (contents.size() > 0) {
							adapter = new SimpleAdapter(getActivity(),
									(List<Map<String, Object>>) contents,
									R.layout.list_item_carer, keys, new int[] {
											R.id.textView1, R.id.textView2,
											R.id.textView3, R.id.textView4,
											R.id.textView5 });
							setListAdapter(adapter);
						}
					} else {
						adapter.notifyDataSetChanged();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					page--;
					if (code != 0) {
						loadFailed(mesage);
					} else {
						loadSuccessed();
						page++;
					}
				}

			}
		});
	}

	protected void setListAdapter(SimpleAdapter adapter) {
		listView.setAdapter(adapter);

	}

	@Override
	public void onStart() {
		super.onStart();

		// When in two-pane layout, set the listview to highlight the selected
		// list item
		// (We do this during onStart because at the point the listview is
		// available.)
		if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity != null) {
			// This makes sure that the container activity has implemented
			// the callback interface. If not, it throws an exception.
			try {
				mCallback = (OnListFragmentSelectedListener) activity;
			} catch (ClassCastException e) {
				e.printStackTrace();
				lg.e(TAG,
						"onAttach:activity must implement OnListFragmentSelectedListener");
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// Set the item as checked to be highlighted when in two-pane layout
		listView.setItemChecked(position, true);
		try {
			IntentExtraDataKeyValue.updateUserInfoToIntent(userListJosnAry
					.getJSONObject(position).toString());
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
			Toast.makeText(getActivity(), "null user&plate", Toast.LENGTH_SHORT)
					.show();
		}
		// Notify the parent activity of selected item
		// mCallback.onArticleSelected(position);
		getActivity()
				.startActivityForResult(
						GlobalVariable.getGlobalInstance().intent
								.setAction(ActivityActionName.CARER),
						IntentExtraDataKey.ACTIVITY_QUESTCODE_UPDATECARERINFO);
	}

	@Override
	public void receiveMessage(Object message) {
		// TODO Auto-generated method stub
		super.receiveMessage(message);
		getData(null);
	}
}